package com.oocl.im.handler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import com.oocl.im.dao.UserDao;
import com.oocl.im.dao.impl.UserDaoImpl;
import com.oocl.im.pojo.MsgPackage;
import com.oocl.im.pojo.Operation;
import com.oocl.im.pojo.User;
import com.oocl.im.util.JsonUtil;

public class RegisterHandler implements Runnable {
	private UserDao userDao;
	private Socket socket;
	private BufferedReader reader;
	private PrintWriter writer;

	public RegisterHandler(Socket socket) {
		super();
		userDao = new UserDaoImpl();
		this.socket = socket;
		try {
			reader = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			writer = new PrintWriter(socket.getOutputStream(), true);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		// the json string of msgPackage
		String msgJson = null;
		try {
			msgJson = reader.readLine();
		} catch (IOException e1) {
			e1.printStackTrace();
			// can not read json,later work make no sense.
			return;
		}
		MsgPackage msgPackage = JsonUtil.stringToObject(msgJson);
		String register = msgPackage.getSender();
		String password = msgPackage.getContent();
		if (msgPackage.getOpeartion() == Operation.REGISTER) {
			User user = userDao.findByName(register);
			// package for send to register
			MsgPackage msgPackage2 = new MsgPackage();
			msgPackage2.setOpeartion(Operation.REGISTER);
			if (user != null) {
				msgPackage2.setContent("This name has been registed");

			} else {
				// i is effected row
				int i = userDao.addUser(new User(null, register, password));
				if (i == 1) {
					msgPackage2.setContent("regist success!");
				} else {
					msgPackage2.setContent("error,please regist again!");
				}
			}
			String msgJson2 = JsonUtil.objectToString(msgPackage2);
			writer.println(msgJson2);

		}
		try {
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
